package com.sunzhe.cms.web;

import com.ibeetl.admin.core.conf.PasswordConfig;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CoreFileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.*;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.CmsArticle;
import com.ibeetl.cms.service.CmsArticleService;
import com.ibeetl.cms.web.query.CoreFileQuery;
import com.ibeetl.member.annotation.LoginRequired;
import com.ibeetl.member.entity.Member;
import com.ibeetl.member.rbac.MemberLoginInfo;
import com.ibeetl.member.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 会员空间接口
 */
@Controller
public class MemberSpaceController {
    private final Log log = LogFactory.getLog(this.getClass());
    private final String MODEL = "space";

    @Autowired
    PasswordConfig.PasswordEncryptService passwordEncryptService;

    @Autowired
    MemberService memberService;

    @Autowired
    CmsArticleService articleService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    HttpRequestLocal httpRequestLocal;

    @Autowired
    CoreFileService coreFileService;

    @Autowired
    Environment env;

    @Autowired
    HttpServletRequest request;

    @RequestMapping(MODEL + "")
    public ModelAndView index() {
        Member member = platformService.getCurrentMember();
        ModelAndView view = new ModelAndView(platformService.getTpl() + "/" + MODEL + "/index.html");
        return view;
    }
    @GetMapping(MODEL + "")
    public ModelAndView index(@RequestParam(required = true) String domain) {
        Member member = memberService.getMemberByDomain(domain);
        ModelAndView view = new ModelAndView(platformService.getTpl() + "/" + MODEL + "/index.html");
        return view;
    }


    @RequestMapping(MODEL + "/{page}.do")
    @LoginRequired()
    public ModelAndView spacePage(HttpServletRequest request, @PathVariable("page") String page) {
        Member member = platformService.getCurrentMember();
        System.out.println(this.getClass().getName() + "访问" + MODEL + "/" + page);
        ModelAndView view = new ModelAndView(platformService.getTpl() + "/" + MODEL + "/" + page + ".html");
        return view;
    }

    @RequestMapping(MODEL + "/view/{page}.do")
    public ModelAndView viewPage(@PathVariable("page") String page) {
        System.out.println(this.getClass().getName() + "访问" + MODEL + "/" + page);
        ModelAndView view = new ModelAndView(platformService.getTpl() + "/" + MODEL + "/view/" + page + ".html");
        return view;
    }

    @PostMapping(MODEL + "/member/update.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult update(@Validated({ValidateConfig.UPDATE.class})  Member member ) {
        member = this.memberService.queryById(member.getId());
        member = ParamUtil.initParameterObj(request, member);
        String[] type2Array = request.getParameterValues("type2Value[]");
        String type2Str = StringUtils.join(type2Array,",");
        member.setType2(type2Str);
        int success = memberService.upsert(member);
        if (success > 0) {
            this.platformService.setLoginMember(member);
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败！");
        }
    }

    @PostMapping(MODEL + "/member/reg.json")
    @ResponseBody
    public JsonResult<Integer> add(@Validated(ValidateConfig.ADD.class) Member member) throws IOException {
        if (member != null && member.getId() != null) {
            return this.update(member);
        }

        member.setCreateTime(new Date());
        member.setPassword(passwordEncryptService.password(member.getPassword()));

        String photo = request.getParameter("photo");
        if (StringUtils.isBlank(photo)) {
            member.setPhoto(String.valueOf(getPhotoFileId()));
        }

        String[] type2Array = request.getParameterValues("type2Value[]");
        String type2Str = StringUtils.join(type2Array,",");
        member.setType2(type2Str);

        memberService.upsert(member);
        return JsonResult.success(member.getId());
    }

    public Long getPhotoFileId() {
        // 随机分配头像
        String faceWebDir = FileItem.getRoot(env) + File.separator + "face";
        File faceDir = new File(faceWebDir);

        File[] faceFiles = faceDir.listFiles();
        int faceCount = faceFiles.length;
        Random random = new Random();
        int count = random.nextInt(faceCount);
        File faceFile = faceFiles[count];
        String faceFileName = faceFile.getName();

        String path = File.separator + "face" + File.separator + faceFileName;
        String uuid = UUIDUtil.uuid();
        FileItem fileItem = fileService.createFileItem(faceFile.getName(), "头像", path, uuid);

        return fileItem.getId();
    }

    @PostMapping(MODEL + "/login.json")
    @ResponseBody
    public JsonResult<MemberLoginInfo> login(String loginName, String password) {
        MemberLoginInfo info = memberService.login(loginName, password);
        Member member = info.getMember();
        // 记录登录信息到session
        this.platformService.setLoginMember(info.getMember());
        return JsonResult.success(info);
    }

    /**
     * 管理员重置用户密码
     *
     * @return
     */
    @PostMapping(MODEL + "/changePassword.json")
    @ResponseBody
    @LoginRequired()
    public JsonResult changePassword(String oldpassword, String password,String repassword) {
        if (StringUtils.equals(password, repassword)) {
            Member m = this.platformService.getCurrentMember();
            m = this.memberService.queryById(m.getId());
            if (StringUtils.equals(m.getPassword(), oldpassword)) {
                memberService.resetPassword(m.getId(), password);
                return new JsonResult().success();
            } else return new JsonResult().failMessage("原始密码不正确");



        } else {
            return new JsonResult().failMessage("两次密码输入不一致");
        }

    }

    @PostMapping(MODEL + "/changeDomain.json")
    @ResponseBody
    @LoginRequired()
    public JsonResult changeDomain(@RequestParam(required = true)String domain) {
        Member currentMember = memberService.getMemberById(this.platformService.getCurrentMember().getId());
        Member member = memberService.getMemberByDomain(domain);

        if (member != null) {
            if (currentMember.getId().intValue() != member.getId().intValue()) {//如果已存在的用户与当前用户是同一用户，则验证通过
                return JsonResult.failMessage("域名已被占用");
            } else {
                return JsonResult.successMessage("域名可以使用");
            }
        } else {
            return JsonResult.successMessage("域名可以使用");
        }
    }

    @PostMapping(MODEL + "/savePhoto.json")
    @ResponseBody
    public JsonResult savePhoto(String cropFileId) throws IOException {
        Member currentMember = memberService.getMemberById(this.platformService.getCurrentMember().getId());
        currentMember.setPhoto(cropFileId);
        this.memberService.update(currentMember);
        this.platformService.setLoginMember(currentMember);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/article/update.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult articleAddUpdate(CmsArticle article ) {
        article = this.articleService.queryById(article.getId());
        if (article == null) {
            article = new CmsArticle();
            article.setCreateTime(new Date());
        };
        article = ParamUtil.initParameterObj(request, article);
        article.setShowTime(new Date());
        Member member = platformService.getCurrentMemberOnly();
        article.setMemberId(member.getId());
        int success = articleService.upsert(article);
        if (success > 0) {
            this.platformService.clearArticleCache();
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败！");
        }
    }
    @PostMapping(MODEL + "/article/delete.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        articleService.batchDelCoreArticle(idList);
        this.platformService.clearArticleCache();
        return new JsonResult().success();
    }

    @RequestMapping(MODEL + "/topBg/list.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult<PageQuery> fileList(CoreFileQuery condition) {
        String pageSize = request.getParameter("pageSize");
        String pageNo = request.getParameter("page");
        if (StringUtils.isBlank(pageSize)) pageSize = "10";
        if (StringUtils.isBlank(pageNo)) pageNo = "1";

        PageQuery<CmsArticle> page = coreFileService.queryByCoreFileQuery(condition, NumberUtils.toLong(pageSize),NumberUtils.toLong(pageNo));
        return JsonResult.success(page);
    }

    @RequestMapping(MODEL + "/member/topBg/delete.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult<PageQuery> topBgDel(String id) {
        Member member = platformService.getCurrentMember();
        this.memberService.removeTopBg(member.getId());
        this.platformService.setLoginMember(this.memberService.queryById(member.getId()));
        return JsonResult.success();
    }

    @RequestMapping(MODEL + "/member/topBg/save.json")
    @LoginRequired()
    @ResponseBody
    public JsonResult<PageQuery> topBgSave(String  bgId) {
        Member member = platformService.getCurrentMember();
        this.memberService.updateTopBg(bgId, member.getId());
        this.platformService.setLoginMember(this.memberService.queryById(member.getId()));
        return JsonResult.success();
    }
}
